'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
    async index() {
        const { ctx } = this;
        ctx.body = 'hi, egg';
    }
    //新增的函数
    async put(){
        let {ctx,service} = this;

        let {title,author,num,status,important,time} = ctx.request.body;

        if(title && author && num && status && important && time){
            try{    
                await service.home.put(title,author,num,status,important,time);
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //修改
    async update(){
        let {ctx,service} = this;

        let {title,author,num,status,important,id} = ctx.request.body;

        if(title && author && num && status && important && id){
            try{    
                await service.home.update(title,author,num,status,important,id);
                ctx.body = {
                    code:1,
                    msg:'修改成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //删除
    async del(){
        let {ctx,service} = this;

        let {id} = ctx.query;

        if(id){
            try{
                await service.home.del(id);
                ctx.body = {
                    code:1,
                    msg:'删除成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'删除失败'
            }
        }
    }
    //查询
    async booklist(){
        let {ctx,service} = this;
        //起始下标 (pagenum-1)*count
        let {start=0,count=2} = ctx.query;
        let list = await service.home.booklist(start,count);
        //总数量
        let total = await service.home.total();
        ctx.body = {
            code:1,
            data:list,
            total:total[0]['count(*)']
        }
    }
}

module.exports = HomeController;
